package io.renren.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.renren.modules.sys.user.SecurityUser;
import io.renren.modules.sys.user.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;


/**
 * 公共字段，自动填充
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_DATE = "createTime";
    private final static String CREATOR = "creator";
    private final static String UPDATE_DATE = "updateTime";
    private final static String UPDATER = "updater";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        long now = System.currentTimeMillis();

        //创建者
        this.setInsertFieldValByName(CREATOR, user.getUserId(), metaObject);
        //创建时间
        this.setInsertFieldValByName(CREATE_DATE, now, metaObject);

        //更新者
        this.setInsertFieldValByName(UPDATER, user.getUserId(), metaObject);
        //更新时间
        this.setInsertFieldValByName(UPDATE_DATE, now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新者
        this.setUpdateFieldValByName(UPDATER, SecurityUser.getUserId(), metaObject);
        //更新时间
        this.setUpdateFieldValByName(UPDATE_DATE, System.currentTimeMillis(), metaObject);
    }
}
